<template>
  <div v-if="render.data==='exchangePhone'" :class="'text-message ' + (isMine ? 'my-text' : '')">
    <div class="message-body-span">
      <span v-if="isMine" class="message-body-span-text">交换电话请求已发送</span>
      <span v-if="!isMine&&(render.extension.agree===null||render.extension.agree===false)" class="message-body-span-text">对方请求交换电话</span>
      <span v-if="!isMine&&render.extension.agree===true" class="message-body-span-text">电话：{{render.extension.phone}}</span>
    </div>
    <div v-if="!isMine&&render.extension.agree===null" class="message-body-btn">
      <div @click="exchangePhoneCall(1)" class="operation-btn">拒绝</div>
      <div @click="exchangePhoneCall(2)" class="operation-btn">同意</div>
    </div>
  </div>
  <div v-else-if="render.data==='sendResume'" :class="'text-message ' + (isMine ? 'my-text' : '')">
    <div class="message-body-span">
      <span class="message-body-span-text">{{ isMine?'已向对方发送简历请求':'对方想发送个人简历' }}</span>
    </div>
    <div v-if="!isMine&&render.extension.agree===null" class="message-body-btn">
      <div @click="resumeCall(1)" class="operation-btn">拒绝</div>
      <div @click="resumeCall(2)" class="operation-btn">同意</div>
    </div>
  </div>
  <div v-else-if="render.data==='getResume'" :class="'text-message ' + (isMine ? 'my-text' : '')">
    <div class="message-body-span">
      <span class="message-body-span-text">{{ isMine?'已向对方获取简历':'对方想获取个人简历' }}</span>
    </div>
    <div v-if="!isMine&&render.extension.agree===null" class="message-body-btn">
      <div @click="resumeCall(3)" class="operation-btn">拒绝</div>
      <div @click="resumeCall(4)" class="operation-btn">同意</div>
    </div>
  </div>
  <div v-else-if="render.data==='resume'" :class="'text-message ' + (isMine ? 'my-text' : '')">
    <div class="message-body-span">
      <span style="cursor: pointer" @click="openResume(render.extension)" class="message-body-span-text">{{render.description}}(点击查看)</span>
    </div>
  </div>
  <div v-else-if="render.data==='invited'" :class="'text-message ' + (isMine ? 'my-text' : '')">
    <div class="message-body-span">
      <span class="message-body-span-text">{{isMine?'已向对方发送面试邀请【请在小程序端查看】':'对方向您发起了一个面试邀请【请在小程序端查看】'}}</span>
    </div>
  </div>
  <div v-else-if="render.data==='c2cCalling' || render.data === 'groupCalling'" :class="'text-message ' + (isMine ? 'my-text' : '')">
    <div class="message-body-span">
      <span class="message-body-span-text">{{ render.extension }}</span>
    </div>
  </div>
  <div v-else-if="render.data==='position'" v-loading="positionLoading" class="position-card">
    <PositionItem class="position-item" v-if="position" :data="position" ></PositionItem>
  </div>
</template>

<script>
import {formateTime, getPhoneByImUserID, getToAccount} from "@/utils/im";
import {findAllJobById} from '@/api/position.js'
import {followAdd, getResumeUrl} from "@/api/im";
import Vue from "vue";
import PositionItem from "@/components/PositionItem/PositionItem.vue";

export default {
  name: "MessageCustom",
  components: {PositionItem},
  props: {
    message: {
      type: Object
    },
    isMine: {
      type: Boolean,
      default: true
    }
  },
  watch:{
    message: {
      handler: function(newVal) {
        this.render=this.parseCustom(newVal);
      },
      immediate: true,
      deep: true
    }
  },
  data(){
    return{
      position:null,
      render:null,
      phone:null,
      positionLoading:true,
    }
  },
  mounted() {
    this.phone=this.$store.getters.user.mobile;
  },
  methods:{
    parseCustom(message){
      let renderDom={...message.payload};
      switch (renderDom.data){
        case 'invited':
        case 'getResume':
        case 'sendResume':
        case 'exchangePhone':
          if(renderDom.extension.length>0){
            renderDom.extension=JSON.parse(renderDom.extension);
          }
          break;
        case 'position':
          if (renderDom.extension.length > 0) {
            renderDom.extension = JSON.parse(renderDom.extension);
            findAllJobById({
              id: renderDom.extension.id
            }).then((res) => {
              this.position=res
            }).finally(()=>{
              this.positionLoading=false;
            })
          }
          break;
        case 'resume':
          break;
        default:
          const callingmessage = JSON.parse(renderDom.data);
          if (callingmessage.businessID === 1) {
            if (message.conversationType === 'C2C') {
              const c2cText = this.extractCallingInfoFromMessage(message);
              renderDom.data='c2cCalling';
              renderDom.extension=c2cText
            }
          }
          break;
      }
      return renderDom;
    },
    // 解析音视频通话消息
    extractCallingInfoFromMessage(message) {
      const callingmessage = JSON.parse(message.payload.data);
      if (callingmessage.businessID !== 1) {
        return '';
      }
      const objectData = JSON.parse(callingmessage.data);
      switch (callingmessage.actionType) {
        case 1: {
          if (objectData.call_end >= 0 && !callingmessage.groupID) {
            console.log(objectData.call_end)
            return `结束时间：${formateTime(objectData.call_end)}`;
          }
          if (callingmessage.groupID) {
            return '结束群聊';
          }
          if (objectData.data && objectData.data.cmd === 'switchToAudio') {
            return '切换语音通话';
          }
          if (objectData.data && objectData.data.cmd === 'switchToVideo') {
            return '切换视频通话';
          }
          return '发起通话';
        }
        case 2:
          return '取消通话';
        case 3:
          if (objectData.data && objectData.data.cmd === 'switchToAudio') {
            return '切换语音通话';
          }
          if (objectData.data && objectData.data.cmd === 'switchToVideo') {
            return '切换视频通话';
          }
          return '已接听';
        case 4:
          return '拒绝通话';
        case 5:
          if (objectData.data && objectData.data.cmd === 'switchToAudio') {
            return '切换语音通话';
          }
          if (objectData.data && objectData.data.cmd === 'switchToVideo') {
            return '切换视频通话';
          }
          return '无应答';
        default:
          return '';
      }
    },
    //打开简历
    openResume(url){
      window.open(url)
    },
    //处理简历逻辑
    resumeCall(type){
      const to=getToAccount(this.message.conversationID,this.message.conversationType);
      let thisMessage=JSON.parse(JSON.stringify(this.message));
      let extension=JSON.parse(thisMessage.payload.extension);
      if(type===1||type===3){//拒绝
        extension.agree=false;
        thisMessage.payload.extension=JSON.stringify(extension);
        this.tim.modifyMessage(thisMessage)
        //发送拒绝文本
        const message=this.tim.createTextMessage({
          to,
          conversationType:this.message.conversationType,
          payload:{
            text:type===1?'拒绝接收简历':'拒绝发送简历'
          }
        })
        this.$sendTIMMessage(message)
      }else{
        const loading=Vue.prototype.$loading({
          fullscreen:true,
          text:'加载中',
        })
        const mobile =type===2? getPhoneByImUserID(this.message.from):getPhoneByImUserID(this.message.to);
        getResumeUrl({
          mobile
        }).then((res) => {
          extension.agree=true
          thisMessage.payload.extension=JSON.stringify(extension);
          this.tim.modifyMessage(thisMessage)
          const resume = res;
          const message=this.tim.createCustomMessage({
            to,
            conversationType:this.message.conversationType,
            payload:{
              data:'resume',
              description:type===2?'已接收简历':'已发送简历',
              extension:resume,
            }
          })
          this.$sendTIMMessage(message)
          if(type===2){
            this.submitSwapResume(mobile,2)
          }else{
            this.submitSwapResume(getPhoneByImUserID(this.message.from),1)
          }
        }).catch(() => {
          this.$message.error('获取简历地址失败');
        }).finally(()=>{
          loading.close()
        })
      }
    },
    //处理交换电话逻辑
    exchangePhoneCall(type){
      const to=getToAccount(this.message.conversationID,this.message.conversationType);
      let thisMessage=JSON.parse(JSON.stringify(this.message));
      let extension=JSON.parse(thisMessage.payload.extension);
      let message;
      if(type===1){//拒绝
        extension.agree=false;
        //发送拒绝文本
        message=this.tim.createTextMessage({
          to,
          conversationType:this.message.conversationType,
          payload:{
            text:'拒绝交换电话'
          }
        })
      }else{
        extension.agree=true
        message=this.tim.createTextMessage({
          to,
          conversationType:this.message.conversationType,
          payload:{
            text:`电话：${this.phone}`
          }
        })
      }
      thisMessage.payload.extension=JSON.stringify(extension);
      this.tim.modifyMessage(thisMessage)
      this.$sendTIMMessage(message)
    },
    //提交交换简历的记录
    submitSwapResume(mobile, followType) {
      const data={
        follow: 5,
        mobile,
        followType
      }
      followAdd(data)
    },
    $sendTIMMessage(message) {
      this.$bus.$emit('sendMessage', {
        detail: {
          message
        }
      });
      this.tim.sendMessage(message).then(() => {
      }).catch(() => {
        this.$message.error('消息发送失败');
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.text-message {
  display: flex;
  flex-direction: column;
  justify-content: center;
  max-width: 225px;
  line-height: 26px;
  padding: 6px 12px;
  background: #FFF;
  /* border: 1px solid #D9D9D9; */
  box-shadow: 0 0 3px 0 #ccc;
  border-radius: 2px 10px 10px 10px;
}

.my-text {
  border-radius: 10px 2px 10px 10px;
  border: 1px solid rgba(0, 110, 255, 0.30);
  background: rgba(0, 110, 255, 0.10);
}

.message-body-span {
  display: flex;
  justify-content: center;
  align-items: center;
  /*justify-content: flex-start;*/
  flex-wrap: wrap;
  outline: none;
  font-size: 14px;
  color: #333333;
  position: relative;
  max-width: 60vw;
}

.message-body-span-text {
  width: 100%;
  display: inline;
  word-wrap: break-word;
  word-break: break-all;
}

.message-body-span-image {
  display: inline-block;
  width: 16px;
  height: 16px;
  margin: 0 2px;
}
.message-body-btn{
  display: flex;
  flex-direction: row;
  align-items: center;
  border-top: 1px solid $lightGray;
  padding-top: 3px;
  .operation-btn{
    flex-grow: 1;
    border-right: 1px solid $lightGray;
    text-align: center;
    font-size: 14px;
    cursor: pointer;
  }
  .operation-btn:last-child{
    border-right: none;
  }
}
.position-item{
  width: 400px;
  box-shadow: 0 0 10px #ccc;
}
.position-card{
  min-height: 222px;
}
</style>
